<template>
  <l-layout class="learun-el-form-left" :top="layoutTop" :topMove="false">
    <template #top>
      <el-form
        :model="formData"
        :rules="rules"
        size="mini"
        labelPosition="left"
        labelWidth="100px"
        ref="form"
        class="pd-8"
      >
        <el-row :gutter="32">
          <el-col :span="12">
            <el-form-item
              :label="$t('数据库')"
              prop="lr_sass_dataschema_f_DbCode"
            >
              <el-select
                v-model="formData.lr_sass_dataschema_f_DbCode"
                :placeholder="$t('请选择')"
                @change="dbChange"
              >
                <el-option-group
                  v-for="group in lr_dblinkTree"
                  :key="group.id"
                  :label="group.label"
                >
                  <el-option
                    v-for="item in group.children"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('数据表')"
              prop="lr_sass_dataschema_f_Table"
            >
              <el-input
                readonly="readonly"
                v-model="formData.lr_sass_dataschema_f_Table"
              >
                <span
                  slot="append"
                  @click="handleAddTable('lr_sass_dataschema_f_Table')"
                >
                  <el-button slot="append" icon="el-icon-more" />
                </span>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('关联表')" prop="lr_sass_dataschema_f_HasRTable">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="formData.lr_sass_dataschema_f_HasRTable"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item
                :label="$t('父级字段')"
                prop="lr_sass_dataschema_f_ParentId"
              >
                <l-select
                  v-model="formData.lr_sass_dataschema_f_ParentId"
                  :options="fieldOptions"
                >
                </l-select>
              </el-form-item>
            </el-col>
          <template v-if="formData.lr_sass_dataschema_f_HasRTable">
            <el-col :span="12">
              <el-form-item
                :label="$t('关联字段')"
                prop="lr_sass_dataschema_f_Field"
              >
                <l-select
                  v-model="formData.lr_sass_dataschema_f_Field"
                  :options="fieldOptions"
                >
                </l-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('关联表')"
                prop="lr_sass_dataschema_f_RTable"
              >
                <el-input
                  readonly="readonly"
                  v-model="formData.lr_sass_dataschema_f_RTable"
                >
                  <span
                    slot="append"
                    @click="handleAddTable('lr_sass_dataschema_f_RTable', true)"
                  >
                    <el-button slot="append" icon="el-icon-more" />
                  </span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="$t('关联表字段')"
                prop="lr_sass_dataschema_f_RField"
              >
                <l-select
                  v-model="formData.lr_sass_dataschema_f_RField"
                  :options="rfieldOptions"
                >
                </l-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item
              :label="$t('排序')"
              prop="lr_sass_dataschema_f_Sort"
            >
              <el-input-number
                controlsPosition="default"
                v-model="formData.lr_sass_dataschema_f_Sort"
                :placeholder="$t('请输入')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div class="l-rblock pd-8" style="padding-bottom: 0;">
      <div class="l-auto-window">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane class="l-tabs-container" :label="$t('数据')" name="tab0">
            <l-select-panel
              v-model="dataValue"
              :columns="dataColumns"
              :isPage="true"
              :loadSelectTable="loadSelectTable"
              :multiple="true"
              model="client"
              :valueKey="pkey"
              v-if="showDataTable"
              ref="dbTableDataTable"
            >
            </l-select-panel>
          </el-tab-pane>
          <el-tab-pane
            class="l-tabs-container"
            :label="$t('列设置')"
            name="tab1"
          >
            <l-table :columns="columns" :dataSource="tableColumns">
              <template v-slot:rTable="scope">
                <el-input
                  size="mini"
                  readonly="readonly"
                  v-model="scope.row.rTable"
                >
                  <span
                    slot="append"
                    @click="handleSelectTable(scope.row, 'rTable')"
                  >
                    <el-button slot="append" icon="el-icon-more" />
                  </span>
                </el-input>
              </template>
            </l-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <l-codetable-selectdialog
      :visible.sync="dbtableSelectdialog"
      :dbCode="formData.lr_sass_dataschema_f_DbCode"
      :isOkClose="false"
      :multiple="false"
      @select="dbSelect"
    >
    </l-codetable-selectdialog>
  </l-layout>
</template>

<script>
const api = window.$api.sass.dataschema;
const apiCodeTable = window.$api.data.codeTable;
const apidbTable = window.$api.data.dbTable;

export default {
  props: {
    objectId: String,
  },
  data() {
    return {
      moduleCode: "sass_dataschema",
      activeName: "tab0",
      formData: {
        lr_sass_dataschema_f_DbCode: "", // 数据库编码
        lr_sass_dataschema_f_Table: "", // 数据表
        lr_sass_dataschema_f_HasRTable: "", // 是否有关联表
        lr_sass_dataschema_f_Field: "", // 和关联表对应的字段
        lr_sass_dataschema_f_RTable: "", // 关联表
        lr_sass_dataschema_f_RField: "", // 关联表字段
        lr_sass_dataschema_f_ParentId:"",

        lr_sass_dataschema_f_Sort: "", // 排序字段
      },
      rules: {
        lr_sass_dataschema_f_DbCode: [
          {
            required: true,
            message: this.$t("请选择"),
          },
        ],
        lr_sass_dataschema_f_Table: [
          {
            required: true,
            message: this.$t("请选择"),
          },
        ],

        lr_sass_dataschema_f_Field: [
          {
            required: true,
            message: this.$t("请选择"),
          },
        ],
        lr_sass_dataschema_f_RTable: [
          {
            required: true,
            message: this.$t("请选择"),
          },
        ],
        lr_sass_dataschema_f_RField: [
          {
            required: true,
            message: this.$t("请选择"),
          },
        ],
      },

      columns: [
        { label: "字段", prop: "name", minWidth: "100" },
        { label: "描述", prop: "coment", minWidth: "100" },
        { label: "关联表", prop: "rTable", minWidth: "100" },
      ],

      dbtableSelectdialog: false,

      selectRow: null,
      tableNameField: "",
      isNotMain: false,

      tableMap: {},
      dbTableDatas: {},

      tableColumns: [],
      showDataTable: true,
      
      dataValue: ""
    };
  },
  computed: {
    fieldOptions() {
      return this.getCols(this.formData.lr_sass_dataschema_f_Table);
    },
    rfieldOptions() {
      console.log('rfieldOptions');
      return this.getCols(this.formData.lr_sass_dataschema_f_RTable);
    },
    layoutTop() {
      if (this.formData.lr_sass_dataschema_f_HasRTable) {
        return 180;
      } else {
        return 132;
      }
    },

    dataColumns() {
      const res = [];
      this.tableColumns.forEach((t) => {
        res.push({
          label: t.coment ? `${t.name}(${t.coment})` : t.name,
          prop: t.name.toLowerCase(),
          minWidth: "160",
        });
      });
      if (res.length == 0) {
        res.push({
          label: "",
          prop: "",
          minWidth: "160",
        });
      }
      return res;
    },
    pkey() {
      if (this.tableColumns.length == 0) {
        return "";
      }
      const key = this.tableColumns.find((t) => t.isPrimary).name.toLowerCase();
      return key;
    },
  },
  methods: {
    // 添加数据表
    handleAddTable(name, isNotMain) {
      if (this.formData.lr_sass_dataschema_f_DbCode) {
        this.selectRow = this.formData;
        this.tableNameField = name;
        this.isNotMain = isNotMain;

        this.dbtableSelectdialog = true;
      } else {
        this.$message({
          message: this.$t("请选择数据库"),
          type: "warning",
        });
      }
    },
    handleSelectTable(row, name) {
      if (this.formData.lr_sass_dataschema_f_DbCode) {
        this.selectRow = row;
        this.tableNameField = name;
        this.isNotMain = true;
        this.dbtableSelectdialog = true;
      } else {
        this.$message({
          message: this.$t("请选择数据库"),
          type: "warning",
        });
      }
    },
    async dbSelect(obj, showLoading, hideLoading) {
      showLoading();
      const tableName = obj[0].f_TableName;

      await this.loadCols(tableName, this.formData.lr_sass_dataschema_f_DbCode);
      

      if (!this.isNotMain) {
        this.showDataTable = false;
        this.tableColumns = this.tableMap[tableName] || [];
      }

      hideLoading();
      this.$set(this.selectRow, this.tableNameField, tableName);
      this.dbtableSelectdialog = false;
      if (!this.isNotMain) {
        this.dataValue = "";
        setTimeout(() => {
          this.showDataTable = true;
          this.$nextTick(() => {
            this.$refs.dbTableDataTable.init();
          });
        });
      }
    },
    async loadCols(tableName,dbcode){
      if (!this.tableMap[tableName]) {
        const codeTables = await this.$awaitWraper(
          apiCodeTable.getList(
            dbcode,
            tableName
          )
        );
        if (codeTables) {
          this.tableMap[tableName] = codeTables[0].lr_db_codecolumnsList.map(
            (t) => ({
              id: t.f_DbColumnName,
              name: t.f_DbColumnName,
              csType: t.f_CsType,
              isIdentity: t.f_IsIdentity == 1,
              isPrimary: t.f_IsPrimaryKey == 1,
              isNullable: t.f_IsNullable == 1,
              coment: t.f_Description,
            })
          );
        }
      }
    },


    getCols(tableName) {
      if (!tableName) {
        return [];
      }

      const cols = this.tableMap[tableName] || [];
      return cols.map((t) => ({
        label: t.coment ? `${t.name}(${t.coment})` : t.name,
        value: t.name,
      }));
    },

    dbChange() {
      this.tableMap = {};
      this.dbTableDatas = {};
    },

    async loadSelectTable() {
      const tableName = this.formData.lr_sass_dataschema_f_Table;
      const dbCode = this.formData.lr_sass_dataschema_f_DbCode;

      if(!tableName || !dbCode){
        return [];
      }
      if (!this.dbTableDatas[tableName]) {
        this.dbTableDatas[tableName] = await this.loaddbTableData(
          dbCode,
          tableName
        );
      }
      let data = this.dbTableDatas[tableName];
      return data;
    },

    async loaddbTableData(dbCode, tableName) {
      let queryData = {
        code: dbCode,
        tableName: tableName,
      };
      const data = await this.$awaitWraper(apidbTable.getDataList(queryData));
      return data || [];
    },

    // 重置表单
    resetForm() {
      this.$formClear(this.$refs.form);
      this.activeName = "tab0";
      this.tableColumns  =[];
      this.tableMap = {};
      this.dbTableDatas = {};
      setTimeout(() => {
        this.showDataTable = true;
        this.$nextTick(() => {
          this.$refs.dbTableDataTable.init();
        });
      });
    },
    // 校验表单
    async validateForm() {
      if (!(await this.$formValidateWraper(this.$refs.form))) {
        return false;
      }

      if(this.dataValue.length == 0){
        this.$message({
          type: "warning",
          message: this.$t('请勾选数据'),
        });
        return false;
      }

      return true;
    },
    // 设置表单数据
    async setForm(data) {
      this.showDataTable = false;

      const schema = JSON.parse(data.f_Schema);
      this.tableColumns = schema.columns;
      this.dataValue = schema.data;

      this.tableMap[data.f_Table] =  schema.columns;
      if(data.f_RTable){
        await this.loadCols(data.f_RTable,data.f_DbCode);
      }

      setTimeout(() => {
        this.showDataTable = true;
        this.$nextTick(() => {
          this.$refs.dbTableDataTable.init();
        });
      });

      this.$setFormData(this.formData, data, "lr_sass_dataschema");
    },
    // 获取表单数据
    getForm() {
      const formData = this.$getFormData(this.formData, "lr_sass_dataschema");
      formData.f_ObjectId = this.objectId;

      const schema = {
        columns: this.tableColumns,
        data: this.dataValue,
      };

      formData.f_Schema = JSON.stringify(schema);
      return formData;
    },
    async loadFormData({ keyValue /*,params,node*/ }) {
      //  keyValue 流程中相当于流程processId,params 传递参数,node 流程节点
      const data = await this.$awaitWraper(api.get(keyValue));
      if (data) {
        this.setForm(data);
        return true;
      } else {
        return false;
      }
    },
    async saveForm({ keyValue, isEdit /*,code,node*/ }) {
      // isEdit 是否更新数据, keyValue 流程中相当于流程processId,code 表示流程中的操作码,node 流程节点
      const postData = this.getForm();
      if (isEdit) {
        // 编辑
        return await this.$awaitWraper(api.update(keyValue, postData));
      } else {
        // 新增
        postData.f_Id = keyValue;
        return await this.$awaitWraper(api.add(postData));
      }
    },
  },
};
</script>
